
package mdoc.ejbsample;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import java.util.HashSet;
import java.util.List;

@Stateless(mappedName="Cinema@Remote")
@Remote(Cinema.class)
public class CinemaBean implements Cinema {
    @PersistenceContext
	private EntityManager entityManager = null;
    
    public HashSet<SalleProg> getAllSalleProg() {
	Query q = entityManager.createNamedQuery("findAllSallesProg");
	return new HashSet<SalleProg>(q.getResultList());
    }
    
    public HashSet<Film> getAllFilm() {
	Query q = entityManager.createNamedQuery("findAllFilms");
	return new HashSet<Film>(q.getResultList());
    }
    
    public Film createFilm(String name) {
	Film res = findByName(name);
		
	if(res == null) {
	    res = new Film();
	    res.setName(name);
	    entityManager.persist(res);
	}
	
	return res;
    }

	public Film findFilm(int id) {
		Film res = entityManager.find(Film.class, Integer.valueOf(id));
		// here, you can modify res because it is always 
		// managed by the persistence context
		//		res.setName("Bip");
		return res;
	}

	public Film findByName(String name) {
		Query q = entityManager.createNamedQuery("findFilmByName");
		//Query q = entityManager.createQuery("select f from Film f where f.name = :fname");
 		q.setParameter("fname", name);
 		List<Film> res = q.getResultList();
 		if(res.size() == 0)
 			return null;
 		else
 			return res.get(0);
	}

	public void update(Film film) {
		// this film is detached (it is a copy), we must merge it with the persistence context 
		entityManager.merge(film);
	}

	@Override
	public void reserve(Seance seance, Utilisateur u) {
		// TODO Auto-generated method stub
		int pl = seance.getPlaces();
		if (pl < seance.getProg().getSalle().getCapacite() && u.solde() > 8){
			seance.setPlaces(pl-1);
			u.debite(8);
		}	
	}
}
